;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Purchase.Price", [])
        .controller("PriceCtrl", ["$scope", "$state", "ybWidget", "ybHttp","EventBus", "MESG_TYPE", "$filter", "UserContextService", "$timeout", function ($scope, $state, ybWidget, ybHttp,EventBus, MESG_TYPE, $filter, UserContextService, $timeout) {
            $scope.activeFlag = [true, false, false, false];
            $scope.tabFlag = {};
            $scope.markInfo = {
                allCheckedBill: false,
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/purchasePrice/export"),
                sectionParam: {ids: []},
                allUrl: ybHttp.RequestUrl("device", "/purchasePrice/exportAll")
            };
            $scope.condition = {};
            $scope.dataList = [];
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.tableConfig = {
                fixedWidth: 200,
                scrollWidth: 1450,
                tableCol: [
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "单位",
                        dataField: "unit",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购单价",
                        dataField: "price",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "供货商名称",
                        dataField: "supplierName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "更新时间",
                        dataField: "endUpdateTime",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "替换零件",
                        dataField: "replaceMaterialsNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "替换零件中文名",
                        dataField: "replaceMaterialsDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 160,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        getDataList();
                        break;
                    default:
                        break;
                }
            };

            $scope.addPlan = function () {
                $scope.changeTab(1);
                $scope.tabFlag.type = 1;
                $scope.orderObj = {
                    materialsList: [],
                    purchasePrice: '',
                    provisionalPrice: 0
                };
                $scope.supplierObj = {};
            };

            $scope.editPlan = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.tabFlag.type = 2;
                    $scope.changeTab(2);
                });
            };
            $scope.delData = function (delType, id) {
                var service = "device";
                var reqUrl = "/purchasePrice/batchDelete";
                var ids = [];
                if (delType === "single") {
                    ids.push(id);
                }
                if (delType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked) {
                            ids.push($scope.dataList[i].id);
                        }
                    }
                    if (ids.length === 0) {
                        ybWidget.ShowMessage('请选择需要删除的行');
                        return;
                    }
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, ids).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                })
            };

            //选择供货商
            $scope.selectDealer = function () {
                var param = {
                    name: "供货商",
                    type: "supplierName4Price"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.supplierObj.supplierOrgName = data.companyName;
                    $scope.supplierObj.supplierOrgId = data.supplierOrgId;
                    $scope.supplierObj.supplierCode = data.supplierCode;
                    $scope.supplierObj.supplierClassName = data.supplierClassName;
                    $scope.supplierObj.supplierClassId = data.supplierClassId;
                })
            };

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
            };

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.saveDataEditor = function () {
                if ($scope.orderObjShow.price === '') {
                    ybWidget.ShowToaster('error', '采购单价不可为空');
                    return;
                }
                var service = "device";
                var reqUrl =  "/purchasePrice/update";
                var param = {
                    id: $scope.orderObjShow.id, 
                    materialsNo: $scope.orderObjShow.materialsNo,
                    materialsDes: $scope.orderObjShow.materialsDes,
                    unit: $scope.orderObjShow.unit,
                    materialsType: $scope.orderObjShow.materialsType,
                    supplierCode: $scope.orderObjShow.supplierCode,
                    supplierOrgName: $scope.orderObjShow.supplierName,
                    supplierOrgId: $scope.orderObjShow.supplierOrgId,
                    supplierClassName: $scope.orderObjShow.supplierClassName,
                    supplierClassId: $scope.orderObjShow.supplierClassId,
                    price: $scope.orderObjShow.price,
                    provisionalPrice: $scope.orderObjShow.provisionalPrice,
                };

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };

            $scope.saveData = function () {
                if ($scope.orderObj.materialsList.length === 0) {
                    ybWidget.ShowToaster('error', '零件不可为空');
                    return;
                }
                if (!$scope.supplierObj || Object.values($scope.supplierObj).length === 0) {
                    ybWidget.ShowToaster('error', '供货商不可为空');
                    return;
                }
                if ($scope.orderObj.purchasePrice === '') {
                    ybWidget.ShowToaster('error', '采购单价不可为空');
                    return;
                }
                var service = "device";
                var reqUrl =  "/purchasePrice/add";
                var param = {
                    materialsNo: $scope.orderObj.materialsList[0].materialsNo,
                    materialsDes: $scope.orderObj.materialsList[0].materialsDes,
                    unit: $scope.orderObj.materialsList[0].unit,
                    materialsType: $scope.orderObj.materialsList[0].materialsType,
                    supplierCode: $scope.supplierObj.supplierCode,
                    supplierName: $scope.supplierObj.supplierOrgName,
                    supplierOrgId: $scope.supplierObj.supplierOrgId,
                    supplierClassName: $scope.supplierObj.supplierClassName,
                    supplierClassId: $scope.supplierObj.supplierClassId,
                    price: $scope.orderObj.purchasePrice,
                    provisionalPrice: $scope.orderObj.provisionalPrice,
                };

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
                getDataList();
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {left: $scope.tableConfig.fixedWidth + "px"}
                };
            };

            $scope.importPrice = function () {
                var param = {
                    name: "采购价格",
                    templateReqService: "device",
                    templateReqUrl: "/purchasePrice/download",
                    importReqService: "device",
                    importReqUrl: "/purchasePrice/importBuyPlan",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };

            function viewDetail(item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.changeTab(3);
                });
            }

            function getDetail(item) {
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', '/purchasePrice/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.orderObjShow = item;
                    return resp.value;  
                });
            }

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    curRow: -1
                };
                var service = "device";
                var reqUrl = "/purchasePrice/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.price = $filter("decimalPlaces")(item.price/100, 2);
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = Math.ceil(resp.value.total / resp.value.pageSize);
                    $scope.dataList = resp.value.list;
                });
            }

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }



            var btnPermissionCode = {
                purchasePriceMaintenanceAdd: window.ActionCode.purchasePriceMaintenanceAdd,
                purchasePriceMaintenanceImport: window.ActionCode.purchasePriceMaintenanceImport,
                purchasePriceMaintenanceEdit: window.ActionCode.purchasePriceMaintenanceEdit,
                purchasePriceMaintenanceDel: window.ActionCode.purchasePriceMaintenanceDel,
            };
            $scope.btnPermission = {
                purchasePriceMaintenanceAdd: true,
                purchasePriceMaintenanceImport:true,
                purchasePriceMaintenanceEdit: true,
                purchasePriceMaintenanceDel: true,
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);